/*
 * a simiple suggest plugins
 * html :
 * 		<div class="suggest-container customerClass">
 * 			<ul>
 * 				<li><span class="value">内容</span></li>
 * 			       ...
 * 			</ul>
 * 		</div>
 * use  :
 $(#elem).suggest(options)
 * author:  lj
 * date : 2015/11/24
 */
define(function(require, exports, module) {


	var defaults = {
		type: 'default', // default & email
		items: [],
		customerClass: '',
		container: null,
		onshow:$.noop,
		onSelected: $.noop,
		highlight : 'current',
		selected : 'selected',
		wrapper:null
	}

	function Suggest(options, elem) {

		this.$elem = elem;
		this.options = $.extend(true, {}, defaults, options);
		this.init();

	}



	Suggest.prototype = {

		init: function() {
			this.suggestContainer = $('<ul class="suggest-container ' + this.options.customerClass + '"></ul>');

			this.options.container = this.options.container || this.$elem.parent();
			if(this.options.wrapper){
				this.options.container.append(this.options.wrapper);
				this.options.container.find('.overview').append(this.render(this.options.items));
			}else{
				this.options.container.append(this.render(this.options.items));
			}

			this.bindEvent();

		},

		//调用render可以重新渲染模板
		render: function(items) {

			var tmp = '',
				i;
			if (items) {

				for (i = 0; i < items.length; i++) {

					var item = items[i],
						item_id = $.isPlainObject(item) && item.id ? 'item_id=' + item.id : '',
						disable = $.isPlainObject(item) && item.disable ? 'disable' : '',
						value = $.isPlainObject(item) ? item.value : item;
					if(items.length-1==i){
						tmp += '<li ' + item_id + ' class="suggest-li-last ' + disable + '"><div class="value">' + value + '</div></li>'
					}else{
						tmp += '<li ' + item_id + ' class="' + disable + '"><div class="value">' + value + '</div></li>'
					}
				}

				this.suggestContainer.html(tmp);

				this.items = this.suggestContainer.find('li:not(.disable)');

				return this.suggestContainer;

			}

		},

		bindEvent: function() {

			this.suggestPanleEvent();

			this.inputEvent();
		},
		suggestPanleEvent: function() {
			var _this = this;
			this.suggestContainer.on({
				mouseover:function(){
					_this.setHighlight($(this));
				},
				mousedown:function(){
					_this.onselected($(this));
					_this.setSelected($(this));
					return false;
				}
			},'li:visible:not(.disable)');


		},
		onselected: function(item) {
			var _this = this;
			var isinput = this.isInput();
			if(_this.$elem.is('#select-country')){
				var value = $(".value", item).html()+'<a href="javascript:void(0) "class="arrow"></a>';
			}else{
				var value = $(".value", item).html();
			}
			isinput ? _this.$elem.val(value) : _this.$elem.html(value);
			_this.hide();
			//if(!_this.isIE()){
			_this.$elem.trigger('focusout');
			//}
			//callback
			$.isFunction(_this.options.onSelected) && _this.options.onSelected(item);
			$(document).off('keydown.suggest');
		},
		isIE:function(){
			var isIE=!!window.ActiveXObject;
			var isIE6=isIE&&!window.XMLHttpRequest;
			var isIE8=isIE&&!!document.documentMode;
			var isIE7=isIE&&!isIE6&&!isIE8;
			return isIE6 || isIE7 || isIE8;

		},
		inputEvent: function() {
			var _this = this;
			var index = -1;
			var elem = this.$elem;
			var isinput = _this.isInput();
			var doc = $(document);
			if (!isinput) {
				//如果不是input标签 keydown事件绑定到document上
				elem.on('click.suggest', function() {

					doc.on('keydown.suggest', function(e) {

						var items = _this.items;

						if (e.keyCode == 40) {

							index = index < items.length - 1 ? ++index : 0;
							_this.setHighlight(items.eq(index));
						}
						if (e.keyCode == 38) {

							index = index < 1 ? items.length - 1 : --index;
							_this.setHighlight(items.eq(index));
						}
						if (e.keyCode == 13) {

							_this.onselected(items.eq(index));
						}
						return false;
					})
					doc.on('click.suggest', function(e) {
						if($(e.target).closest('#scrollbar1').length>0){
							return;
						}
						_this.hide();
						doc.off('keydown.suggest');
					})

					if($('#scrollbar1').css('visibility')=='hidden' || $('#scrollbar1').css('display')=='none'){
						_this.show();

					}else{
						_this.hide();

					}

					return false;
				})

			} else {

				var items ;

				elem.on('keydown.suggest', function(e) {

					items = _this.getItems();
					//key down
					if (e.keyCode == 40) {
						index = index < items.length - 1 ? ++index : 0;
						_this.setHighlight(items.eq(index));
						return false;
					}
					//key up
					if (e.keyCode == 38) {
						index = index < 1 ? items.length - 1 : --index;
						_this.setHighlight(items.eq(index));
						return false;
					}
					if(e.keyCode == 13){

						if(index < 0){

						}else{
							_this.onselected(items.eq(index));
							index = -1;
						}
						return false;
					}


				})
				elem.on('keyup.suggest', function(e) {

					if(e.keyCode == 13){
						_this.hide();
						setTimeout(function(){
							_this.$elem.trigger('focusout');
						},100)
						return true;
					}
				})



				if(_this.options.type === 'email'){

					elem.on('keyup.email',function(e){
						if(e.keyCode == 13){

							return ;
						}
						var items = _this.items;

						var val = elem.val();

						var _index = val.indexOf('@');

						if (val == '') {

							_this.hide();

						} else {

							_this.show();
						}
						//replace
						items.each(function(i) {

							var item = $(this).find('.value');
							var itemText = item.html().toString().toLowerCase();
							if(val.toLowerCase() == itemText){
								_this.hide();
								return;
							}

							if(_index > 0){
								var subs = val.substring(_index);
								var leftsub = val.substring(0,_index);
								item.html(leftsub + _this.options.items[i]);
								if(itemText.indexOf(subs) < 0){
									$(this).hide();
								}else{
									$(this).show();
								}
								return;
							}
							item.html(val + _this.options.items[i]);
						})
						if(_this.getItems().length == 0){
							_this.hide();
						}

						elem.on('focusout',function(){
							_this.hide();
						})

					})

				}


			}

		},
		getItems : function(){

			return this.suggestContainer.find('li:visible:not(.disable)');
		},
		/**
		 判断元素是否input标签
		 不是input标签 键盘事件绑定在document上
		 **/
		isInput : function(){
			return this.$elem[0].tagName === "INPUT";
		},
		setHighlight: function(item) {

			var Highlight = this.options.highlight;

			item.addClass(Highlight).siblings().removeClass(Highlight);
		},
		setSelected:function(item){
			var selected = this.options.selected;
			item.addClass(selected).siblings().removeClass(selected);
		},
		//public method
		show: function() {
			this.suggestContainer.show();
			$.isFunction(this.options.onshow) && this.options.onshow();
			this.suggestContainer.closest('.form-item').css('z-index',15);

		},
		hide: function() {
			this.suggestContainer.hide();
			//重置选中样式
			this.items.removeClass(this.options.highlight);
			$('#scrollbar1').hide();
			if($('.suggest-container').css('display')=='none'){
				this.suggestContainer.closest('.form-item').css('z-index',12);
			}
			//$('#select-country .arrow').removeClass('down');
		}
	}

	//REGISTER JQUERY PLUGIN
	$.fn.suggest = function(options) {

		//make sure elem just one 
		if($(this).length ==1 ){
			return new Suggest(options, $(this))
		}else{
			return;
		}

	}

})
